import { View, Picker, Button } from '@tarojs/components'
import { OnGetUserInfoEventDetail } from '@tarojs/components/types/Button'
import { BaseEventOrig } from '@tarojs/components/types/common'
import Taro, { Config, useDidShow, UserInfo, useState } from '@tarojs/taro'
import { BaiduMapResponse } from 'src/types/response'
import { AtButton } from 'taro-ui'
import { Header } from './components/Header/Header'
import { HealthReport } from './components/HealthReport/HealthReport'
import './index.less'
import { Card } from '../../components/Card/Card'

export function Index() {
  const [isAuth, setAuthState] = useState(true)
  const [userInfo, setUserInfo] = useState<UserInfo>({} as UserInfo)
  const [city, setCity] = useState('')
  let baidu_location = '';
  const [org_name, setOrg_name] = useState('')
  const [scene, setScene] = useState(0)
  let org_secrt = ""
  useDidShow(async () => {//生命周期钩子
    const senceData=wx.getLaunchOptionsSync() 
    setScene(senceData.scene)
    const setting = await Taro.getSetting()
    console.log("进入首页生命周期，路由为：" + this.$router,"场景值为："+scene)
    if (this.$router.params.org_secrt != "" && this.$router.params.org_secrt != undefined) {
      org_secrt = this.$router.params.org_secrt;
    } else {
      org_secrt = "test0227";
    }
    if (process.env.TARO_ENV == 'weapp') {
      wx.setStorage({
        key: 'org_secrt',
        data: org_secrt
      })
    } else {
      // h5 和 alipay
      localStorage.setItem("org_secrt", org_secrt);
      console.log("local storage" + localStorage)
    }
    console.log("org_secrt为：" + org_secrt)
    await getOrgInfo(org_secrt)
    if (!setting.authSetting['scope.userInfo']) {
      setAuthState(false)
      return
    }
    await getUserInfo()

  })


  const getUserInfo = async () => {
    const { userInfo } = await Taro.getUserInfo()
    setUserInfo(userInfo)
    setAuthState(true)
    await getCity()
  }
  //获取机构信息
  const getOrgInfo = async (org_secrt: string) => {
    Taro.cloud.callFunction({
      name: 'faas',
      data: { method: 'get_org_info', data: { org_secrt: org_secrt } },
      success: res => {
        console.log(res.result.data)
        if (res.result.data.length > 0) {
          setOrg_name(res.result.data[0].org_name);

        }

      },
    })
  }

  const onGetUserInfo = async (result: BaseEventOrig<OnGetUserInfoEventDetail>) => {
    if (result.detail.userInfo) {
      Taro.showToast({ title: '授权登录成功~' })
      await getUserInfo()
      return
    }

    Taro.showModal({
      title: '温馨提示',
      content: '请授权登录哦~',
      showCancel: false,
    })
  }

  const getCity = async () => {
    try {
      await Taro.authorize({
        scope: 'scope.userLocation',
      })

      const { latitude, longitude } = await Taro.getLocation({})

      const { data } = await Taro.request<BaiduMapResponse>({
        url: `https://api.map.baidu.com/geocoder/v2/?ak=lr7Cl7QkbGqH5irqlK5wZvwQ9duK84hc&location=${latitude},${longitude}&output=json`,
      })
      setCity(data.result.addressComponent.city)
    } catch (e) { }
  }

  const toKnowledge = () => {
    Taro.navigateTo({
      url: '/pages/knowledge/index?org_secrt="test0227"',
    })
  }
  const toConnect = () => {

  }
  const toFillReport = () => {
    // Taro.navigateToMiniProgram({
    //   appId: 'wx34b0738d0eef5f78',
    //   path: 'pages/forms/publish?token=ZVLu1c',
    // })

    Taro.navigateTo({
      url: '/pages/reportsubmit/index?org_name=' + org_name + '&org_secrt=' + org_secrt,
    })

  }


  if (!isAuth) {
    return (
      <View className="container">
        {this.props.children}
        <Header city={""} name={""} org_name={""} avatar={""} />
        <View className="content">
          <HealthReport baidu_location={baidu_location} scene={scene} isAuth={isAuth} org_name={org_name} org_secrt={org_secrt} />
          <View className="card-container">
            <AtButton className="" openType="getUserInfo" lang="zh_CN" onGetUserInfo={onGetUserInfo} type="primary">
              微信用户快速登录
            </AtButton>
            <Card onClick={toFillReport} title={'企业校园返工返校登记'} desc={'返工返校登记，查询当前机构情况'} />
            <AtButton className="contactBtn" lang="zh_CN" openType="contact">联系开发者</AtButton>
            <Card onClick={toConnect} title={'联系开发者'} desc={'如需提供定制机构，请联系开发者'} />

            <Card onClick={toKnowledge} title={'防疫工具合集'} desc={'防疫小妙招、网课、肺炎咨询等'} />
          </View>
        </View>
      </View>
    )
  }
  return (
    <View className="container">
      {this.props.children}
      <Header city={city} name={userInfo.nickName} org_name={org_name} avatar={userInfo.avatarUrl} />
      <View className="content">
        <HealthReport baidu_location={baidu_location} isAuth={isAuth} org_name={org_name} org_secrt={org_secrt} />
        <View className="card-container">
          <Card onClick={toFillReport} title={'企业校园返工返校登记'} desc={'输入返校日期车次，查询病患同行情况'} />
          <AtButton className="contactBtn" lang="zh_CN" openType="contact">联系开发者</AtButton>
          <Card onClick={toConnect} title={'联系开发者'} desc={'如需提供定制机构，请联系开发者'} />

          <Card onClick={toKnowledge} title={'防疫工具合集'} desc={'防疫小妙招、网课、肺炎咨询等'} />
        </View>
      </View>
    </View>

 

}

Index.config = {
  navigationBarTitleText: '首页',
} as Config
